package com.jzo2o.orders.base.handler;

import cn.hutool.db.DbRuntimeException;
import com.jzo2o.common.expcetions.CommonException;
import com.jzo2o.orders.base.enums.OrderPayStatusEnum;
import com.jzo2o.orders.base.enums.OrderStatusEnum;
import com.jzo2o.orders.base.model.dto.OrderSnapshotDTO;
import com.jzo2o.orders.base.model.dto.OrderUpdateStatusDTO;
import com.jzo2o.orders.base.service.IOrdersCommonService;
import com.jzo2o.statemachine.core.StatusChangeEvent;
import com.jzo2o.statemachine.core.StatusChangeHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author 随缘而愈
 * @version 1.0
 * @description TODO
 * @date 23/4/2024 上午9:15
 */
@Component("order_payed")
@Slf4j
public class OrderPayedHandler implements StatusChangeHandler<OrderSnapshotDTO> {
    @Resource
    private IOrdersCommonService ordersService;

    /**
     * 订单支付处理逻辑
     *
     * @param bizId   业务id
     * @param bizSnapshot 快照
     */
    @Override
    public void handler(String bizId, StatusChangeEvent statusChangeEventEnum, OrderSnapshotDTO bizSnapshot) {
        log.info("支付成功事件处理逻辑开始，订单号：{}", bizId);
        // 统一订单管理 状态更新
        OrderUpdateStatusDTO orderUpdateStatusDTO = new OrderUpdateStatusDTO();
        orderUpdateStatusDTO.setId(bizSnapshot.getId());
        orderUpdateStatusDTO.setOriginStatus(OrderStatusEnum.NO_PAY.getStatus());//原始状态
        orderUpdateStatusDTO.setOriginStatus(OrderStatusEnum.DISPATCHING.getStatus());//目标状态
        orderUpdateStatusDTO.setPayStatus(OrderPayStatusEnum.PAY_SUCCESS.getStatus());//支付成功
        orderUpdateStatusDTO.setTradingOrderNo(bizSnapshot.getTradingOrderNo());//交易单号
        orderUpdateStatusDTO.setTransactionId(bizSnapshot.getThirdOrderId());//第三方单号
        orderUpdateStatusDTO.setPayTime(bizSnapshot.getPayTime());//支付时间
        orderUpdateStatusDTO.setTradingChannel(bizSnapshot.getTradingChannel());//支付渠道
        Integer result = ordersService.updateStatus(orderUpdateStatusDTO);

        if (result <= 0) {
            throw new DbRuntimeException("支付事件处理失败");
        }

    }
}
